<template>
  <div class="food-wrap">
    <div class="food-box-left">
      <div class="title-box" v-if="desk">
        <div class="numberAndDesc">
          <div class="number">{{ desk?.desk_name }}</div>
          <div class="desc" v-if="desk?.desk?.region?.name">桌/{{ desk?.desk?.region?.name }}</div>
        </div>
        <div class="member-people-box">
          <div class="member" @click.stop="onClickBindMember">
            <div class="name" v-if="desk?.user && desk?.user?.grade">
              会员：{{ desk?.user?.real_name }}
            </div>
            <div class="name" v-else>绑定会员</div>
            <img class="icon" src="@/assets/images/home/edit-icon.png" alt="" />
          </div>
          <div class="people" @click.stop="onClickEditUseNum">
            <div class="name">人数：{{ desk?.use_num }}/{{ desk?.desk?.capacity }}</div>
            <img class="icon" src="@/assets/images/home/edit-icon.png" alt="" />
          </div>
        </div>
      </div>

      <div class="order-number-box" v-if="desk && desk.order_id && desk.order_id != '0'">
        <div class="number">订单号：{{ desk.order_id }}</div>
        <div class="discount-btn" @click.stop="onClickPrintMenu">打印菜单</div>
      </div>

      <div class="food-scroll-list">
        <template v-if="selectedListState.length">
          <div
            class="scroll-list-item"
            :class="{ 'scroll-list-item-active': activeIndexState === index }"
            v-for="(item, index) in selectedListState"
            :key="item.id + '-' + index"
            @click.stop="handleSelectLocal(index, item)"
          >
            <div class="number">{{ index >= 10 ? index : '0' + (index + 1) }}</div>
            <div class="desc-box">
              <div class="name-box">
                <div class="wait-btn" v-if="item.is_wait === 1">等</div>

                <div class="name">{{ item.foodName || item.foodGroupName }}</div>
                <div class="gift-btn" v-if="item.is_present === 1 || item.is_present === 2">
                  赠品
                </div>

                <div class="print-btn" v-if="item.print === 1">打印</div>
                <div class="print-btn" v-else>不打印</div>
              </div>
              <div class="price-box">
                <div class="orginPrice">
                  <div>￥{{ item.foodPrice }}</div>
                  <div class="discount-btn" v-if="item.discount && item.discount !== 10">
                    ×{{ item.discount }}折
                  </div>
                </div>
                <div class="count">×{{ item.foodNum }}{{ item.foodUnit }}</div>
                <div class="discount-price">￥{{ item.foodTotalPrice }}</div>
              </div>
              <div class="info-box">
                <div class="sku" v-if="item.foodDescName">{{ item.foodDescName }}</div>
              </div>

              <!-- 显示套餐下面的菜品 -->
              <div
                class="group-food-list"
                v-if="
                  item.foodGroupSelectFoodList &&
                  item.foodGroupSelectFoodList.length > 0 &&
                  item.is_group === 1 &&
                  activeIndexState === index
                "
              >
                <div
                  class="group-food-list-item"
                  v-for="group in item.foodGroupSelectFoodList"
                  :key="group.id"
                >
                  <div class="name">{{ group.sku.foodInfo.name }}</div>
                  <div class="count">×{{ group.num }}</div>
                </div>
              </div>

              <!-- 菜品操作按钮 -->
              <div class="btn-list" v-show="activeIndexState === index">
                <div class="btn-item" @click.stop="handleShowSingleWait">等叫</div>
                <div class="btn-item" @click.stop="handleShowSingleGift">
                  {{ item.is_present === 1 || item.is_present === 2 ? '撤赠' : '赠送' }}
                </div>
                <div class="btn-item" @click.stop="handleToggleSinglePrint">
                  {{ item.print === 1 ? '不打印' : '打印' }}
                </div>
                <div class="btn-item" @click.stop="handleShowSingleDiscount">打折</div>
                <div class="btn-item" @click.stop="actionDeleteSelected(emit)">
                  删除
                </div>
              </div>
            </div>
          </div>
        </template>
        <div class="no-data-box" v-else>
          <NotData desc="请在右侧点击菜品进行点菜" />
        </div>
      </div>

      <div class="settlement-content" v-if="selectedListState.length">
        <div class="count-price-box">
          <div class="count">数量：{{ totalCount }}份</div>
          <div class="price-box">
            <div class="total-price">总金额：￥{{ totalPrice }}</div>
            <div class="actual-price">
              <span>应付金额：</span>
              <div>￥{{ totalPay }}</div>
            </div>
          </div>
        </div>
        <div class="btn-list">
          <div class="btn-item" @click.stop="handleClearAll">全部清空</div>
          <div class="btn-item" v-if="mode === 'desktopPage'" @click.stop="actionSendSelected(1)">
            先送
          </div>
          <div
            class="btn-item"
            @click.stop="
              handleBackExit()
            "
          >
            返回
          </div>
        </div>
        <!-- 预约模式显示预定按钮 -->
        <div class="settlement-btn" v-if="mode === 'appointmentPage'" @click.stop="handleAppointmentOrder">预定</div>
        <!-- 桌台模式显示下单/加菜按钮 -->
        <div class="settlement-btn" v-else-if="hasOrder" @click.stop="actionSendSelected(2)">加菜</div>
        <div class="settlement-btn" v-else @click.stop="actionSendSelected(2)">下单</div>
      </div>
    </div>

    <div class="food-box-right">
      <div class="button-list">
        <div class="button-item-count-box" v-if="selectedListState.length">
          <div class="count">{{ activeCountState }}</div>
          <div class="add-delete-box">
            <button class="delete" @click.stop="handleCount('delete')">-</button>
            <button class="add" @click.stop="handleCount('add')">+</button>
          </div>
        </div>
        <el-button
          class="button-item"
          :class="{
            'button-item-disabled':
              (btn.needSelectFood && (activeIndexState === -1 || !selectedListState.length)) ||
              btn.disabled
          }"
          v-for="(btn, idx) in actionsList"
          :key="btn.name + idx"
          :disabled="
            (btn.needSelectFood && (activeIndexState === -1 || !selectedListState.length)) ||
            btn.disabled
          "
          @click.stop="handleActionBar(idx, emit)"
        >
          {{ btn.name }}
        </el-button>
      </div>
    </div>
  </div>
  <!-- 会员绑定弹框 -->
  <MemberBindDialog
    v-model:modelValue="showMemberDialog"
    :desk-detail="desk"
    @success="updateDesk"
  />
  <!-- 修改人数弹框 -->
  <DinerDialog v-model="showDinerDialog" :desk-detail="desk" @success="emit('createOrAdd')" />
  <!-- 规格/数量弹框 -->
  <SpecificationQuantityDialog
    v-model:modelValue="showSpecQuantityDialog"
    :currentFoodData="specFoodData"
    :loading="specLoading"
    @confirm="onSpecConfirm"
  />

  <!-- 套餐选择弹框 -->
  <FoodPackageDialog
    v-model:visible="showPackageDialog"
    :currentGroupFoodId="packageData?.foodGroupId || ''"
    :selectedCurrentFoodGroup="packageData"
    @confirm="handlePackageConfirm"
  />
  <!-- 下单前改价弹框 -->
  <PreOrderFoodPriceDialog
    v-model:modelValue="showPrePriceDialog"
    :currentFood="selectedListState[activeIndexState]"
    @confirm="onPrePriceConfirm"
  />
  <!-- 下单前全部等叫弹框 -->
  <PreOrderWaitDialog v-model:modelValue="showPreWaitDialog" @confirm="onPreWaitConfirm" />
  <!-- 下单前全部赠送弹框 -->
  <PreOrderGiftDialog v-model:modelValue="showPreGiftDialog" @confirm="onPreGiftConfirm" />
  <!-- 下单前全部打折弹框 -->
  <PreOrderDiscountDialog
    v-model:modelValue="showPreDiscountDialog"
    @confirm="onPreDiscountConfirm"
  />

  <!-- 单个菜品等叫弹框 -->
  <SingleWaitDialog
    v-model:modelValue="showSingleWaitDialog"
    :selectedFood="selectedListState[activeIndexState]"
    @confirm="onSingleWaitConfirm"
  />

  <!-- 单个菜品赠送弹框 -->
  <SingleGiftDialog
    v-model:modelValue="showSingleGiftDialog"
    :selectedFood="selectedListState[activeIndexState]"
    @confirm="onSingleGiftConfirm"
    @revoke="onSingleRevokeGiftConfirm"
  />

  <!-- 单个菜品打折弹框 -->
  <SingleDiscountDialog
    v-model:modelValue="showSingleDiscountDialog"
    :selectedFood="selectedListState[activeIndexState]"
    @confirm="onSingleDiscountConfirm"
    @revoke="onSingleRevokeDiscountConfirm"
  />

  <!-- 手写菜品弹框 -->
  <HandwritingFoodDialog
    v-model:modelValue="showHandwritingDialog"
    @confirm="onHandwritingFoodConfirm"
  />
</template>

<script setup lang="ts">
import { computed, defineProps, defineEmits, ref, onMounted, onUnmounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { deskOrderCreateOrderTicket } from '@/api/desktop'
import NotData from '@/components/NotData/Index.vue'
import DinerDialog from '@/views/Home/components/Food/components/DinerDialog.vue'
import MemberBindDialog from '@/views/Home/components/Food/components/MemberBindDialog.vue'
import { useSelectedActions } from '@/views/Diancai/hooks/useSelectedActions'
import { useSingleFoodActions } from '@/views/Diancai/hooks/useSingleFoodActions'
import SpecificationQuantityDialog from '@/views/Home/components/common/SpecificationQuantityDialog.vue'
import PreOrderFoodPriceDialog from '@/views/Home/components/common/PreOrderFoodPriceDialog.vue'
import PreOrderWaitDialog from '@/views/Home/components/common/PreOrderWaitDialog.vue'
import PreOrderGiftDialog from '@/views/Home/components/common/PreOrderGiftDialog.vue'
import PreOrderDiscountDialog from '@/views/Home/components/common/PreOrderDiscountDialog.vue'
import SingleWaitDialog from '@/views/Diancai/components/SingleWaitDialog.vue'
import SingleGiftDialog from '@/views/Diancai/components/SingleGiftDialog.vue'
import SingleDiscountDialog from '@/views/Diancai/components/SingleDiscountDialog.vue'
import HandwritingFoodDialog from '@/views/Diancai/components/HandwritingFoodDialog.vue'
import FoodPackageDialog from '@/views/Diancai/components/FoodPackageDialog.vue'
import messageTips from '@/components/messageTips'
import { deskOrderAddFood, deskOrderAdd } from '@/api/food'
import { useRouter } from 'vue-router'
import { DeskStorageManager } from '@/utils/deskStorage'

// 组件职责
// - 左侧“已点列表”与底部结算区域 + 右侧动作按钮区
// - 内部自维护已点数据与选中态；对外仅暴露“加菜/下单(createOrAdd)”与“动作选择(action)”事件
// - 提供对外方法 addFoodFromMenu(food) 供父组件在右侧菜单点菜时调用

// 类型定义：桌台与已点行
interface Desk {
  id?: string | number
  record_id?: string | number
  desk_name?: string
  desk?: any
  use_num?: number
  order_id?: string
  user?: {
    grade?: any
    real_name?: string
  }
  // 预约相关属性
  user_name?: string
  mobile?: string
  book_time?: string
  keep_time?: string
  book_type?: string
  book_money?: number
  settle_type?: number
  money?: number
  book_num?: number
  book_user_id?: string
  deskIds?: string
  remark?: string
}
interface Selected {
  id?: number
  foodName?: string
  foodGroupName?: string
  foodUnit?: string
  foodNum: number
  foodPrice: number
  foodTotalPrice: number
  foodDescName?: string
  is_wait?: number
  is_present?: number
  print?: number
  discount?: number
  foodGroupSelectFoodList?: any[]
  is_group?: number
  food_sku_id?: string | number
  is_write_food?: number
  write_food_name?: string
  write_food_price?: number
  category_id?: number
  remarks?: string
  status?: number
  wait_time?: string
  making_ids?: number[]
  write_making?: any[]
  taste_ids?: number[]
  write_taste?: any[]
  position?: any[]
  food_ids?: number[]
  foodgroup_id?: number
  present_num?: number
  edit_price?: number
  _raw?: any
}

// 外部入参
// - desk: 桌台/订单基础信息（用于头部展示/弹窗）
// - mode: 页面模式（桌台点菜/预约等）
// - hasOrder: 是否已有订单（决定“下单/加菜”文案）
const props = defineProps<{
  desk: Desk | null
  mode: 'desktopPage' | 'appointmentPage'
  hasOrder: boolean
}>()

// 对外事件
// - createOrAdd: 触发下单/加菜
// - action: 点击右侧动作按钮（传递按钮索引）
// - openPractice: 打开做法面板（传递当前选中菜品数据）
const emit = defineEmits<{
  (e: 'createOrAdd'): void
  (e: 'action', idx: number): void
  (e: 'openPractice', foodData: any): void
  (e: 'openTaste', foodData: any): void
  (e: 'openPosition', foodData: any): void
  (e: 'loadDeskBaseInfo'): void
}>()

// 路由
const router = useRouter()
// 右侧动作按钮改为对象化，由 hook 统一维护
// 是否拦截返回提示

const isInterceptBack = ref(false)

// 内部状态
// - selectedListState: 已点菜品列表（来源于 addFoodFromMenu 聚合）
// - activeIndexState/activeCountState: 当前选中的行与份数，驱动右侧加减器显示
const selectedListState = ref<Selected[]>([])
const activeIndexState = ref(-1)
const activeCountState = ref(0)
const totalCount = computed(() =>
  selectedListState.value.reduce((s, i) => s + Number(i.foodNum || 0), 0)
)
const totalPrice = computed(() =>
  selectedListState.value.reduce((s, i) => s + Number(i.foodPrice || 0), 0).toFixed(2)
)
const totalPay = computed(() =>
  selectedListState.value.reduce((s, i) => s + Number(i.foodTotalPrice || 0), 0).toFixed(2)
)

// 套餐弹窗相关状态
const showPackageDialog = ref(false)
const packageData = ref<any>(null)

const {
  handleSelect,
  handleClearAll,
  handleBack,
  actionDeleteSelected,
  handleCount,
  handleActionBar,
  addFoodFromMenu,
  onPackageConfirm,
  actionsList,
  showSpecQuantityDialog,
  specFoodData,
  specLoading,
  onSpecConfirm,
  showPrePriceDialog,
  onPrePriceConfirm,
  showPreWaitDialog,
  onPreWaitConfirm,
  showPreGiftDialog,
  onPreGiftConfirm,
  showPreDiscountDialog,
  onPreDiscountConfirm,
  onPrePracticeConfirm,
  onPreTasteConfirm,
  onPrePositionConfirm,
  showHandwritingDialog,
  onHandwritingFoodConfirm,
  // 暂存数据管理
  loadDeskCacheData
} = useSelectedActions({
  selectedListState: selectedListState as any,
  activeIndexState: activeIndexState as any,
  activeCountState: activeCountState as any,
  props: props as any,
  desktopBelongTypeRef: props.mode === 'desktopPage' ? 2 : 1,
  emit: (event: string, ...args: any[]) => {
    if (event === 'openPackage') {
      handleOpenPackage(args[0])
    }
  }
})

// 使用单个菜品操作hook
const {
  showSingleWaitDialog,
  showSingleGiftDialog,
  showSingleDiscountDialog,
  handleShowSingleWait,
  handleShowSingleGift,
  handleShowSingleDiscount,
  handleToggleSinglePrint,
  onSingleWaitConfirm,
  onSingleGiftConfirm,
  onSingleRevokeGiftConfirm,
  onSingleDiscountConfirm,
  onSingleRevokeDiscountConfirm
} = useSingleFoodActions({
  selectedListState: selectedListState as any,
  activeIndexState: activeIndexState as any,
  activeCountState: activeCountState as any
})
const handleBackExit = () => {
  router.replace({ path: '/home/food/' + router.currentRoute.value.params.id })
}

// 绑定会员 / 修改人数
const showDinerDialog = ref(false)
const showMemberDialog = ref(false)
const onClickBindMember = () => {
  showMemberDialog.value = true
}
const onClickEditUseNum = () => {
  showDinerDialog.value = true
}
const onClickPrintMenu = async () => {
  if (!props.desk?.id) {
    ElMessage.warning('桌台信息异常')
    return
  }

  if (selectedListState.value.length === 0) {
    ElMessage.warning('请先点菜')
    return
  }
  debugger
  try {
    // 组装菜品列表数组数据（参考老项目的数据结构）
    const foodList = selectedListState.value.map((item: any) => {
      return {
        is_write_food: item.is_write_food || 0, // 是否为手写菜品
        write_food_name: item.write_food_name || '', // 手写菜品名称
        write_food_price: item.write_food_price || 0, // 手写菜品价格
        category_id: item?._raw?.category_id || 0, // 手写的菜品分类id
        food_sku_id: item.food_sku_id || 0, // 菜品规格id
        num: item.foodNum || 1, // 菜品数量
        discount: item.discount || 10, // 当前菜品折扣
        remarks: item.remarks || '', // 备注
        status: item.status || 10, // 菜品状态
        print: item.print, // 是否打印
        wait_time: item.wait_time || '', // 等叫时间
        making_ids: item.making_ids || [], // 做法id集合
        write_making: item.write_making || '', // 手写做法
        taste_ids: item.taste_ids || [], // 口味id集合
        write_taste: item.write_taste || '', // 手写口味名称
        position: item.position || '', // 部位
        is_present: item.is_present || 0, // 是否赠送(0:不赠送,部分赠送  1:单品全部赠送)
        food_ids: item.food_ids || [], // 套餐下面的菜品id集合
        is_group: item.is_group || 0, // 是否为套餐
        foodgroup_id: item.foodgroup_id || 0, // 菜品套餐id
        present_num: item.present_num || 0, // 菜品赠送数量
        edit_price: item.edit_price || 0
      }
    })

    const postDatas = {
      record_id: props.desk.id, // 桌台使用记录ID/主桌台记录ID
      food_list: foodList, // 菜品列表数组
      belong_type: router.currentRoute.value.query.type // 1:全席加菜 2:本桌加菜
    }

    const res = await deskOrderCreateOrderTicket(postDatas)
    if (res.status === 200) {
      ElMessage.success('菜单打印成功')
    } else {
      ElMessage.error(res.data?.message || '打印失败')
    }
  } catch (error) {
    console.error('打印菜单失败:', error)
    ElMessage.error('打印失败')
  }
}
// 刷新基本信息
const updateDesk = () => {
  emit('loadDeskBaseInfo')
}

// 预约菜品处理函数
const handleAppointmentOrder = async () => {
  try {
    const messageInstance: any = await messageTips.message(
      {
        title: '预定',
        content: '确认预定菜品吗？',
        isOnCancel: true,
        onCancelText: '取消',
        onSumbitText: '确定'
      },
      async () => {
        try {
          messageInstance.setLoading(true)
          
          // 组装菜品数据
          const foodList = selectedListState.value.map((item: any) => {
            // 按照老项目 food_list 的数据结构进行映射
            return {
              // 基本信息
              foodName: item.foodName || item.foodGroupName || '',
              food_sku_id: item.food_sku_id || 0,
              foodNum: Number(item.foodNum || 1),
              discount: Number(item.discount || 10),
              foodPrice: Number(item.foodPrice || 0),
              foodTotalPrice: Number(item.foodTotalPrice || 0),
              
              // 手写菜品相关
              is_write_food: item.is_write_food || 0,
              write_food_name: item.write_food_name || '',
              write_food_price: item.write_food_price || 0,
              
              // 做法相关
              making_ids: item.making_ids || [],
              write_making: item.write_making || [],
              
              // 口味相关
              taste_ids: item.taste_ids || [],
              write_taste: item.write_taste || [],
              
              // 部位相关
              position: item.position || [],
              
              // 赠送相关
              is_present: item.is_present || 0,
              remarks: item.remarks || '',
              present_num: item.present_num || 0,
              
              // 状态相关
              status: item.status || 1, // 1：起菜 2:催菜 3：等叫 4：已上菜 5：退菜
              print: item.print || 1, // 1:打印 2:已打印 默认1
              wait_time: item.wait_time || '',
              
              // 套餐相关
              food_ids: item.food_ids || [],
              is_group: item.is_group || 0,
              foodgroup_id: item.foodgroup_id || 0,
              
              // 描述信息
              foodDescName: item.foodDescName || '',
              
              // 价格相关
              edit_price: item.edit_price || 0,
              
              // 会员相关
              isVipUser: item.isVipUser || false,
              
              // 其他字段
              foodUnit: item.foodUnit || '',
              memberPrice: item.memberPrice || 0,
              spec_type: item.spec_type || 10, // 10:单规格 20:多规格
              category_id: item?._raw?.category_id || 0,
              
              // 套餐子菜品（如果有）
              foodGroupSelectFoodList: item.foodGroupSelectFoodList || []
            }
          })
          const actionType = router.currentRoute.value.query.actionType

          if (actionType !== 'bookFood') {
            const bookDialogData = sessionStorage.getItem('bookDialogData')
            if (bookDialogData) {
              const data = JSON.parse(bookDialogData)
              data.foodList = foodList
              sessionStorage.setItem('bookDialogData', JSON.stringify(data))
            }
            router.replace({ path: '/book' })
            return;
          }

          // 先获取预约详情，再更新菜品
          const bookId = router.currentRoute.value.query.bookId
          if (!bookId) {
            ElMessage.error('未找到预约ID，无法保存菜品')
            return
          }

          // 1. 先获取当前预约详情
          const { deskBookDetail, deskBookEdit } = await import('@/api/book')
          const bookDetailRes = await deskBookDetail({ book_id: bookId })
          
          if (!bookDetailRes || bookDetailRes.status !== 200) {
            ElMessage.error('获取预约详情失败')
            return
          }

          const bookDetail = bookDetailRes.data.detail
          
          // 2. 构建更新数据（保留原有预约信息，只更新菜品列表）
          const appointmentPayload = {
            book_id: bookId,
            food_list: foodList,
            // 使用从API获取的预约信息
            user_name: bookDetail.user_name || '',
            mobile: bookDetail.mobile || '',
            use_num: bookDetail.use_num || 1,
            book_time: bookDetail.book_time.text || '',
            keep_time: bookDetail.keep_time || '',
            book_type: bookDetail.book_type || '',
            book_money: bookDetail.book_money || 0,
            settle_type: bookDetail.settle_type.value || 20,
            pay_type: bookDetail.pay_type,
            money: bookDetail.money || 0,
            book_num: bookDetail.book_num || 1,
            book_user_id: bookDetail.book_user_id || '',
            deskIds: bookDetail.deskIds || '',
            remark: bookDetail.remark || ''
          }

          // 3. 调用编辑预约接口更新菜品
          const res = await deskBookEdit(appointmentPayload)
          
          if (res && res.status === 200) {
            ElMessage.success('预定成功')
            isInterceptBack.value = true
            // 跳转回预约页面
            router.replace({ path: '/book' })
            DeskStorageManager.clearAllDeskData()
          } else {
            ElMessage.error('预定失败')
          }
          
        } finally {
          messageInstance.setLoading(false)
          messageInstance.close && messageInstance.close()
        }
      }
    )
  } catch (e) {
    console.log('预约处理失败:', e)
  }
}

// 先送：调用后端接口 deskOrderAddFood，支持选择是否打印
const actionSendSelected = async (status: 1 | 2) => {
  console.log('actionSendSelected', status)

  try {
    const messageInstance: any = await messageTips.message(
      {
        title: status === 2 ? '下单' : '先送',
        content: '确认下单吗？',
        isOnCancel: true,
        onCancelText: '取消',
        onSumbitText: '确定'
      },
      async () => {
        try {
          messageInstance.setLoading(true)
          // 组装单菜品为 food_list
          // const item = sel
          debugger
          const foodList = selectedListState.value.map((item: any) => {
            let food = {
              edit_price: item.edit_price || 0,
              is_write_food: item.is_write_food || 0,
              write_food_name: item.write_food_name || '',
              write_food_price: item.write_food_price || 0,
              category_id: item?._raw?.category_id || 0,
              food_sku_id: item.food_sku_id,
              num: Number(item.foodNum || 1),
              discount: Number(item.discount || 10),
              remarks: item.remarks || '',
              status: item.status || 1, //无状态默认传1
              print: item.print,
              wait_time: item.wait_time || '',
              making_ids: item.making_ids || [],
              write_making: item.write_making || [],
              taste_ids: item.taste_ids || [],
              write_taste: item.write_taste || [],
              position: item.position || [],
              is_present: item.is_present || 0,
              food_ids: item.food_ids || [],
              is_group: item.is_group || 0,
              foodgroup_id: item.foodgroup_id || 0,
              present_num: item.present_num || 0
            }
            return {
              ...food,
              // 特殊字段处理
              model_price: item.is_write_food == 1 ? item.foodPrice : undefined
            }
          })
          const recordId = props.desk?.id
          if (!recordId) {
            ElMessage.error('未找到桌台记录ID，无法先送')
            return
          }
          const payload = {
            record_id: recordId,
            food_list: foodList,
            belong_type: router.currentRoute.value.query.type
          }
          // 通过订单判断是调用下单接口 还是加菜接口
          let feach = props.hasOrder ? deskOrderAddFood : deskOrderAdd

          const res = await feach(payload)
          if (res && res.status === 200) {
            ElMessage.success('下单成功')
            if (status === 1) {
              // 清空选中数据
              selectedListState.value = []
              activeIndexState.value = -1
              activeCountState.value = 0
            } else {
              isInterceptBack.value = true
              // 直接返回桌台
              // handleBack()
              // router.go(-1)
              router.replace({ path: '/home/food/' + router.currentRoute.value.params.id })
            }
            DeskStorageManager.clearAllDeskData()
            // onCreateOrAddSuccess(props.desk?.id?.toString() || props.desk?.record_id?.toString())
            // 返回桌台
          }
        } finally {
          messageInstance.setLoading(false)
          messageInstance.close && messageInstance.close()
        }
      },
      async () => {}
    )
  } catch (e) {
    // ignore
    console.log('e', e)
  }
}

// 生命周期钩子：处理暂存数据的加载和清理
onMounted(() => {
  // 组件挂载时加载暂存数据
  if (props.desk?.id || props.desk?.record_id) {
    loadDeskCacheData(props.desk?.id?.toString() || props.desk?.record_id?.toString())
  }
})

// 监听桌台变化，重新加载暂存数据
watch(
  () => [props.desk?.id, props.desk?.record_id],
  (newVal, oldVal) => {
    if (newVal && newVal !== oldVal) {
      loadDeskCacheData(props.desk?.id?.toString() || props.desk?.record_id?.toString())
    }
  }
)

// 本地处理选择菜品，包含套餐数据逻辑
const handleSelectLocal = (index: number, item: any) => {
  // 调用hook中的handleSelect
  handleSelect(index, item)
}

// 套餐事件处理
const handleOpenPackage = (data: any) => {
  packageData.value = data
  showPackageDialog.value = true
}

const handlePackageConfirm = (data: any) => {
  onPackageConfirm(data)
  showPackageDialog.value = false
  packageData.value = null
}

const handleBackSend = (deskId: string, next: () => void) => {
  if (isInterceptBack.value) {
    isInterceptBack.value = false
    next()
    return
  } else {
    handleBack(deskId, next)
  }
}

defineExpose({
  addFoodFromMenu,
  onPrePracticeConfirm,
  onPreTasteConfirm,
  onPrePositionConfirm,
  loadDeskCacheData,
  handleBackSend,
  isInterceptBack
})
</script>

<style scoped lang="scss">
.food-wrap {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  width: 726px;
  height: 986px;
  box-sizing: border-box;
  background: #ffffff;
  border-radius: 20px;
}
.food-box-left {
  position: relative;
  width: 546px;
  height: 986px;
  box-sizing: border-box;
}
.title-box {
  padding: 12px 24px;
  display: flex;
  align-items: flex-end;
  justify-content: space-between;
  box-sizing: border-box;

  .numberAndDesc {
    display: flex;
    align-items: flex-end;
    margin-right: 24px;

    .number {
      font-size: 30px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      text-align: left;
      color: #333333;
      margin-right: 10px;
    }

    .number-less-size {
      font-size: 28px !important;
    }

    .desc {
      max-width: 100px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
      position: relative;
      top: -4px;
    }
  }

  .member-people-box {
    display: flex;
    align-items: center;

    .member {
      display: flex;
      align-items: center;
      cursor: pointer;

      .name {
        max-width: 130px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;
      }

      .icon {
        flex-shrink: 0;
        width: 24px;
        height: 24px;
        margin-left: 12px;
      }
    }

    .people {
      display: flex;
      align-items: center;
      cursor: pointer;
      margin-left: 30px;

      .name {
        max-width: 100px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        color: #333333;
      }

      .icon {
        flex-shrink: 0;
        width: 24px;
        height: 24px;
        margin-left: 12px;
      }
    }
  }
}
.food-scroll-list {
  height: 686px;
  box-sizing: border-box;
  overflow-y: auto;
  border-radius: 20px 0 0 0;
}
.scroll-list-item {
  padding: 20px 30px 20px 24px;
  display: flex;
  align-items: flex-start;
  border-bottom: 1px solid #e2e2e2;
  cursor: pointer;

  .number {
    font-size: 18px;
    font-family:
      PingFang SC,
      PingFang SC-Bold;
    font-weight: 700;
    color: #666666;
    margin-right: 12px;
  }

  .desc-box {
    flex: 1;

    .name-box {
      display: flex;
      align-items: center;

      .name {
        font-size: 18px;
        font-family:
          PingFang SC,
          PingFang SC-Bold;
        font-weight: 700;
        color: #333333;
        margin-right: 10px;
        max-width: 250px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .gift-btn {
        width: 40px;
        height: 23px;
        line-height: 23px;
        border: 1px solid #ff827a;
        border-radius: 6px;
        font-size: 12px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #ff827a;
        margin-left: 10px;
        cursor: default;
      }
      .wait-btn {
        width: 30px;
        height: 23px;
        line-height: 23px;
        border: 1px solid #ff9500;
        background: #ff9500;
        border-radius: 6px;
        font-size: 12px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #fff;
        margin-right: 10px;
        cursor: default;
      }

      .print-btn {
        width: 52px;
        height: 23px;
        line-height: 23px;
        border: 1px solid #999999;
        border-radius: 6px;
        font-size: 12px;
        font-family:
          PingFang SC,
          PingFang SC-Regular;
        font-weight: 400;
        text-align: center;
        color: #999999;
        margin-left: 10px;
      }
    }
  }
}
.scroll-list-item-active {
  background: #f4f4f4;
}
.price-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  // padding-right: 20px;

  .orginPrice {
    display: flex;
    align-items: center;

    > div {
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
    }

    > span {
      margin-left: 12px;
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #b60112;
    }
  }

  .count {
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    color: #333333;
  }

  .discount-price {
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    color: #333333;
  }
}
.info-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  // margin-top: 8px;
  padding-right: 20px;
  .sku {
    font-size: 14px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    color: #999999;
    max-width: 1.30208rem;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

.btn-list {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20px;

  .btn-item {
    height: 40px;
    line-height: 40px;
    background: #ffffff;
    border: 1px solid #999999;
    border-radius: 12px;
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #333333;
    cursor: pointer;
  }

  .btn-item:hover {
    color: #7c0a03;
    border: 1px solid #7c0a03;
  }
}
.settlement-content {
  position: absolute;
  left: 0;
  bottom: 0;
  box-sizing: border-box;
  height: 224px;
  background: #ffffff;
  box-shadow: 0 -4px 6px rgba(0, 0, 0, 0.04);
  padding: 12px 20px 20px;
  border-radius: 0 0 20px 20px;

  .count {
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    color: #333333;
  }

  .price-box {
    display: flex;
    align-items: flex-end;
    justify-content: space-between;
    margin-top: 10px;

    .total-price {
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
    }

    .actual-price {
      font-size: 18px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
      display: flex;
      align-items: flex-end;

      > div {
        font-size: 24px;
        font-family:
          PingFang SC,
          Bold;
        font-weight: 700;
        color: #7c0a03;
      }
    }
  }
}
.discount-btn {
  border-radius: 6px;
  font-size: 12px;
  margin-left: 10px;
  font-family:
    PingFang SC,
    PingFang SC-Regular;
  font-weight: 400;
  text-align: center;
  color: #7c0a03 !important;
  cursor: default;
}
.order-number-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 21px 32px 21px 24px;
  box-shadow: 0px 4px 6px 0px rgba(0, 0, 0, 0.04);
  border-top: 1px solid #e2e2e2;

  .number {
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    color: #333333;
  }

  .discount-btn {
    width: 90px;
    height: 40px;
    line-height: 40px;
    background: #ffffff;
    border: 1px solid #999999;
    border-radius: 12px;
    font-size: 16px;
    font-family:
      PingFang SC,
      PingFang SC-Regular;
    font-weight: 400;
    text-align: center;
    color: #666666;
    cursor: pointer;
  }
}
.btn-list {
  display: flex;
  align-items: center;
  margin-top: 20px;
}
.btn-item {
  display: inline-block;
  padding: 0 16px;
  height: 44px;
  background: #ffffff;
  border: 1px solid #333333;
  border-radius: 12px;
  line-height: 44px;
  font-size: 18px;
  color: #333333;
  cursor: pointer;
}
.settlement-btn {
  width: 506px;
  height: 52px;
  line-height: 52px;
  background: #7c0a03;
  border-radius: 12px;
  font-size: 18px;
  color: #ffffff;
  cursor: pointer;
  margin-top: 20px;
  user-select: none;
  text-align: center;
}
.food-box-right {
  width: 179px;
  height: 986px;
  box-sizing: border-box;
  padding: 24px 0;
  border-left: 1px solid #f4f4f4;
}
.button-list {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  height: 938px;
}
.button-item-count-box {
  width: 120px;
  height: 120px;
  box-sizing: border-box;
  background: #ffffff;
  border: 1px solid #333333;
  border-radius: 20px;
  overflow: hidden;
}
.button-item-count-box .count {
  height: 59px;
  border-bottom: 1px solid #333333;
  line-height: 59px;
  font-size: 26px;
  text-align: center;
  color: #333333;
}
.add-delete-box {
  display: flex;
  align-items: center;
}
.add,
.delete {
  height: 60px;
  width: 59px;
  line-height: 60px;
  font-size: 26px;
  color: #333333;
  cursor: pointer;
  outline: none;
  border: none;
  background: #fff;
}
.add {
  border-left: 1px solid #333333;
}
.button-item {
  width: 120px;
  height: 48px;
  line-height: 48px;
  border: 1px solid #333333;
  border-radius: 12px;
  font-size: 18px;
  color: #333333;
  text-align: center;
  cursor: pointer;
  margin-left: 0px !important;
}
.button-item-disabled {
  border-color: #d9d9d9 !important;
  color: #bfbfbf !important;
  cursor: not-allowed !important;
}
.no-data-box {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 170px;
  margin-top: 250px;
}

.group-food-list {
  border-top: 1px dashed #7c0a03;
  margin-top: 20px;

  .group-food-list-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-top: 12px;

    .name {
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Bold;
      font-weight: 700;
      color: #333333;
      max-width: 300px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .count {
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
    }

    .money {
      font-size: 16px;
      font-family:
        PingFang SC,
        PingFang SC-Regular;
      font-weight: 400;
      color: #333333;
    }
  }
}
</style>
